import 'package:shared_preferences/shared_preferences.dart';

/// 数据存储工具类
class SPUtils {
  static final String userName = "username";
  static final String password = "password";
  static final String isLogin = "isLogin";
  static final String rememberPassword = "rememberPassword";
  static final String themeIndex = "themeIndex";

  static SPUtils _instance = SPUtils._();

  SPUtils._();

  static SPUtils getInstance() {
    return _instance;
  }

  /// 获取用户名
  Future<String?> getUserName() {
    return getValue<String?>(userName);
  }

  /// 更新用户名
  Future<bool> setUserName(String value) {
    return setValue<String>(userName, value);
  }

  /// 获取密码
  Future<String?> getPassword() {
    return getValue<String?>(password);
  }

  /// 更新密码
  Future<bool> setPassword(String value) {
    return setValue<String>(password, value);
  }

  /// 获取登录状态
  Future<bool?> getIsLogin() {
    return getValue<bool?>(isLogin);
  }

  /// 更新登录状态
  Future<bool> setIsLogin(bool value) {
    return setValue<bool>(isLogin, value);
  }

  /// 获取是否记住密码
  Future<bool?> getRememberPassword() {
    return getValue<bool?>(rememberPassword);
  }

  /// 更新记住密码
  Future<bool> setRememberPassword(bool value) {
    return setValue<bool>(rememberPassword, value);
  }

  /// 获取主题
  Future<int?> getThemeIndex() {
    return getValue<int?>(themeIndex);
  }

  /// 更新主题
  Future<bool> setThemeIndex(int value) {
    return setValue<int>(themeIndex, value);
  }

  /// 设置数据
  Future<bool> setValue<T>(String key, T value) {
    return SharedPreferences.getInstance().then((sp) {
      if (value is int) {
        return sp.setInt(key, value);
      } else if (value is bool) {
        return sp.setBool(key, value);
      } else if (value is double) {
        return sp.setDouble(key, value);
      } else if (value is String) {
        return sp.setString(key, value);
      } else if (value is List<String>) {
        return sp.setStringList(key, value);
      } else {
        throw "不支持设置该类型的数据!";
      }
    });
  }

  /// 获取数据
  Future<T?> getValue<T>(String key) {
    return SharedPreferences.getInstance().then((value) => value.get(key) as T?);
  }
}
